package com.wad.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wad.common.exception.BussinessException;
import com.wad.dto.system.AssginRoleDto;
import com.wad.dto.system.LoginDto;
import com.wad.dto.system.SysUserDto;
import com.wad.entity.system.SysUser;
import com.wad.manager.mapper.SysUserMapper;
import com.wad.manager.mapper.SysUserRoleMapper;
import com.wad.manager.service.SysUserService;
import com.wad.vo.common.ResultCodeEnum;
import com.wad.vo.system.LoginVo;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author wad
 * @date 2023/11/29 14:14
 * @project e-commerce
 **/
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public LoginVo login(LoginDto loginDto) {

        //得到输入的验证码和存储验证码的key的名称
        String captcha = loginDto.getCaptcha();
        String codeKey = loginDto.getCodeKey();
        //根据获取的key，从redis中查找存储的验证码
        String redisCode = redisTemplate.opsForValue().get("user:validate" + codeKey);
        //比较输入的验证码和存储的验证码是否一致
        //如果不一致就提示校验失败
        if (StrUtil.isEmpty(redisCode) || !StrUtil.equals(captcha,redisCode)) {
            throw new BussinessException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        //如果一致就删除redis中的验证码
        redisTemplate.delete("user:validate" + codeKey);
        //先获取提交的用户名
        String userName = loginDto.getUserName();

        //根据用户名查询用户表得到用户信息
        SysUser sysUser=sysUserMapper.selectUserInfoByUserName(userName);

        //如果根据用户名查不到用户信息，即用户不存在，返回错误信息
        if (Objects.isNull(sysUser)){
            throw new BussinessException(ResultCodeEnum.LOGIN_ERROR);
        }
        //如果根据用户名可以查到用户信息，用户存在
        //获取输入的密码，比较输入的密码和数据库中的密码是否一致
        //对输入的密码进行加密，md5算法
        String databasePassword = sysUser.getPassword();
        String inputPassword = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());

        //如果密码一致则登录成功，如果密码不一致就登录失败
        if (!Objects.equals(databasePassword,inputPassword)){
            throw new BussinessException(ResultCodeEnum.LOGIN_ERROR);
        }

        //登录成功，生成用户的唯一标识token
        String token= UUID.randomUUID().toString().replaceAll("-","");
        //把登录成功用户信息放到redis里面
        //key为token，value为用户信息
        redisTemplate.opsForValue().set("user:login"+token,JSON.toJSONString(sysUser),7, TimeUnit.DAYS);
        //返回loginVo对象
        LoginVo loginVo=new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }


    //获取登录用户的信息
    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login" + token);
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }


    @Override
    public void logout(String token) {
        //从redis中直接根据key删除token
        redisTemplate.delete("user:login"+token);
    }


    @Override
    public PageInfo<SysUser> findByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> sysUserList=sysUserMapper.findByPage(sysUserDto);
        PageInfo<SysUser> pageInfo=new PageInfo<>(sysUserList);
        return pageInfo;
    }


    @Override
    public void saveSysUser(SysUser sysUser) {
        //判断用户名不能重复
        String userName = sysUser.getUserName();
        SysUser userInfoByUserName = sysUserMapper.selectUserInfoByUserName(userName);
        if (Objects.nonNull(userInfoByUserName)){
            //根据用户名查询用户是否存在，用户不为空表示用户已存在
            throw new BussinessException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        //密码进行加密
        String md5_password = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        sysUser.setPassword(md5_password);

        //设置status的值 1可用 2不可用
        sysUser.setStatus(1);
        sysUserMapper.save(sysUser);
    }


    @Override
    public void updateSysUser(SysUser sysUser) {
        //判断用户名不能重复
        String userName = sysUser.getUserName();
        SysUser userInfoByUserName = sysUserMapper.selectUserInfoByUserName(userName);
        if (Objects.nonNull(userInfoByUserName)){
            //根据用户名查询用户是否存在，用户不为空表示用户已存在
            throw new BussinessException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        sysUserMapper.update(sysUser);
    }


    @Override
    public void deleteById(Long userId) {
        sysUserMapper.delete(userId);
    }

    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        //根据用户id删除之前用户分配过的角色数据
        sysUserRoleMapper.deleteByUserId(assginRoleDto.getUserId());
        //重新分配数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        for (Long roleId : roleIdList) {
            sysUserRoleMapper.doAssign(assginRoleDto.getUserId(),roleId);
        }
    }
}
